<template>
    <a-drawer
        class="container_edit"
        :visible="visible"
        :title="props.title"
        :width="520"
        @close="onClose"
    >
        <a-spin :spinning="loading">
            <a-form
                ref="refForm"
                :model="form"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-item name="nickName" label="用户昵称">
                    <a-input v-model:value="form.nickName" placeholder="请输入用户昵称" allow-clear />
                </a-form-item>
                <a-form-item name="statusDictId" label="用户状态">
                    <a-select
                        v-model:value="form.statusDictId"
                        placeholder="请选择用户状态"
                        allow-clear
                        :options="dictUserStatus"
                    />
                </a-form-item>
                <a-form-item name="mobile" label="手机号码">
                    <a-input v-model:value="form.mobile" placeholder="请输入手机号码" allow-clear />
                </a-form-item>
                <a-form-item name="email" label="邮箱">
                    <a-input v-model:value="form.email" placeholder="请输入邮箱" allow-clear />
                </a-form-item>
                <template v-for="(userOrg, index) in form.userOrgList">
                    <a-divider>
                        关联单位
                        <Icon
                            class="remove_icon"
                            icon="DeleteOutlined"
                            title="移除关联单位"
                            @click="handleRemoveUserOrg(index)"
                        />
                    </a-divider>
                    <a-form-item name="userOrg.orgId" label="单位">
                        <a-tree-select
                            v-model:value="userOrg.orgId"
                            placeholder="请选择单位"
                            allow-clear
                            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                            :field-names="orgDictFieldNames"
                            :tree-data="orgDictData"
                        />
                    </a-form-item>
                    <a-form-item name="roleIdList" label="角色">
                        <a-select
                            v-model:value="userOrg.roleIdList"
                            placeholder="请选择角色"
                            allow-clear
                            mode="multiple"
                            :options="dictRole"
                        />
                    </a-form-item>
                </template>
                <a-divider />
                <a-form-item :wrapper-col="{ span: 22 }">
                    <a-button style="width: 100%;" type="dashed" @click="handleAddUserOrg">
                        <Icon icon="PlusOutlined" />增加关联单位
                    </a-button>
                </a-form-item>
                <div>
                    <a-button type="primary" @click="handleConfirm">确定</a-button>
                    <a-button style="margin-left: 16px" @click="handleClose">取消</a-button>
                    <a-button style="margin-left: 16px" @click="handleReset">重置</a-button>
                </div>
            </a-form>
        </a-spin>
    </a-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { DictUtil, ObjectUtil } from '@/util';
import { Bus } from '@/plugin';
// Component
import Icon from '@/component/common/Icon.vue';
// Api
import Api from '@/axios/api/user';
import { ApiOrg } from '@/axios/api';
// Model
import { Dict, DictType, Result } from "@/model/common";
import { UserForm, UserDTO, UserOrgForm } from '@/model/user';
import { OrgDictDTO } from '@/model/org';

// 参数
const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: '编辑用户管理',
    },
});

// 变量
const visible = ref(false);
const loading = ref(false);
const labelCol = { span: 4 };
const wrapperCol = { span: 18 };
const refForm = ref();
const form = ref(new UserForm());
const rules = UserForm.rules;

// 新增标识，为false时表示更新
const insertFlag = ref(true);
// 数据变化标识，为true时需要发送更新列表的消息
const dataChangedFlag = ref(false);

// 单位数据字段对应
const orgDictFieldNames = {
    key: 'orgId',
    value: 'orgId',
    label: 'orgName',
    children: 'children',
}
const orgDictData = ref<OrgDictDTO[]>([]);
const dictUserStatus = ref<Dict[]>([]);
const dictRole = ref<Dict[]>([]);

// 方法
onMounted(() => {
    init();
});

const init = () => {
    loadDict();
}

const loadDict = () => {
    ApiOrg.listDictTree().then((res: Result) => orgDictData.value = res.data);
    DictUtil.get(DictType.USER_STATUS).then(res => dictUserStatus.value = res);
    DictUtil.get(DictType.ROLE).then(res => dictRole.value = res);
}

/**
 * 打开编辑页面
 */
const open = (id: string | undefined) => {
    visible.value = true;
    if (id) {
        loadInfo(id);
        insertFlag.value = false;
    } else {
        insertFlag.value = true;
    }
}

/**
 * 关闭编辑页面
 */
const close = () => {
    visible.value = false;
}

/**
 * 页面关闭时的回调
 */
const onClose = () => {
    close();
    if (!insertFlag.value) {
        handleReset();
        form.value.userOrgList.length = 0;
    }
    if (dataChangedFlag.value) {
        Bus.emit('refresh_user');
    }
    dataChangedFlag.value = false;
}

/**
 * 点击确认按钮事件
 */
const handleConfirm = () => {
    refForm.value.validate()
        .then(() => {
            insertFlag.value ? insert() : update();
        })
}

/**
 * 点击取消按钮事件
 */
const handleClose = () => {
    close();
}

/**
 * 点击重置按钮事件
 */
const handleReset = () => {
    refForm.value.resetFields();
}

/**
 * 增加关联单位
 */
const handleAddUserOrg = () => {
    form.value.userOrgList.push(new UserOrgForm());
}

/**
 * 移除关联单位
 */
const handleRemoveUserOrg = (index: number) => {
    form.value.userOrgList.splice(index, 1);
}

/**
 * 新增
 */
const insert = () => {
    loading.value = true;
    Api.insert(form.value)
        .then(() => {
            dataChangedFlag.value = true;
            message.success('新增成功！');
            handleReset();
        })
        .catch((err: Result) => {
            message.error(`新增失败！${err.msg}`);
        })
        .finally(() => {
            loading.value = false;
        });
}

/**
 * 修改
 */
const update = () => {
    loading.value = true;
    Api.update(form.value)
        .then(() => {
            dataChangedFlag.value = true;
            message.success('修改成功！');
            handleClose();
        })
        .catch((err: Result) => {
            message.error(`修改失败！${err.msg}`);
        })
        .finally(() => {
            loading.value = false;
        });
}

/**
 * 获取信息
 */
const loadInfo = (id: string) => {
    loading.value = true;
    Api.info(id)
        .then((res: Result) => {
            ObjectUtil.copy(res.data, form.value);
        })
        .finally(() => {
            loading.value = false;
        });
}

// 定义组件对外暴露的内容
defineExpose({
    open
})
</script>

<style lang="less" scoped>
.remove_icon {
    &:hover {
        color: @primary-color;
    }
}
</style>
